#!/usr/bin/env python

"""
Copyright (c) 2009 Timothe Faudot

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""

#GUI
import sys
import wx
import wx.lib.mixins.listctrl  as  listmix

#plotting
import matplotlib
matplotlib.interactive( True )
matplotlib.use( 'WXAgg' )

#samazama
import thread
import random
from time import sleep as slp
from time import time
from os import remove

#audio
from sndobj import *
import pyaudio
import wave

#PYAUDIO constants
chunk = 1024

class PlotPanel (wx.Panel):
    """
    The PlotPanel has a Figure and a Canvas. OnSize events simply set a 
    flag, and the actual resizing of the figure is triggered by an Idle event.
    """
    def __init__( self, parent, color=None, dpi=None, **kwargs ):
        from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
        from matplotlib.figure import Figure

        # initialize Panel
        if 'id' not in kwargs.keys():
            kwargs['id'] = wx.ID_ANY
        if 'style' not in kwargs.keys():
            kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE
        wx.Panel.__init__( self, parent, **kwargs )

        # initialize matplotlib stuff
        self.figure = Figure( None, dpi )
        self.canvas = FigureCanvasWxAgg( self, -1, self.figure )
        self.SetColor(color)

        self.draw()


    def SetColor( self, rgbtuple=None ):
        """Set figure and canvas colours to be the same."""
        if rgbtuple is None:
            rgbtuple = wx.SystemSettings.GetColour( wx.SYS_COLOUR_BTNFACE ).Get()
        clr = [c/255. for c in rgbtuple]
        self.figure.set_facecolor( clr )
        self.figure.set_edgecolor( clr )
        self.canvas.SetBackgroundColour( wx.Colour( *rgbtuple ) )

    def draw(self): pass # abstract, to be overridden by child classes


class mYPlotPanel(PlotPanel):
    """ plots the velocity of each beat """
    def __init__( self, parent, **kwargs ):
        # initiate plotter
        self.whens = []
        self.vels = []
        
        PlotPanel.__init__( self, parent, **kwargs )
        
        pixels = (500, 265)
        self.SetSize( pixels )
        self.canvas.SetSize( pixels )
        self.figure.set_size_inches( float( pixels[0] )/self.figure.get_dpi(),
                                     float( pixels[1] )/self.figure.get_dpi() )
        self.SetColor( (255,255,255) )
        self.subplot.set_xlabel("Time (ms)", fontsize = 8)
        self.subplot.set_ylabel("Vel.", fontsize = 8)
        self.subplot.set_ylim([0, 127])

    def draw( self ):
        #"""Draw data."""
        if not hasattr(self, 'subplot'):
            self.subplot = self.figure.add_subplot(111)
        self.subplot.plot(self.whens, self.vels, '-b', markersize=10)
        self.subplot.plot(self.whens, self.vels, '.r', markersize=10)


    def setMidiEvents(self, whens, vels):
        self.subplot.cla()
        self.whens = whens
        self.vels = vels
        self.subplot.set_xlim([0, max(whens)])



class MidiEvent():
    def __init__(self, when, velocity):
        self.when = when
        self.vel = velocity
        
    def __str__(self):
        return "Midi Event: vel:%f at time:%f"%(self.vel, self.when)

class CommandPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)
        
        self.btnStart = wx.Button(self, -1, "Start MIDI input")
        self.Bind(wx.EVT_BUTTON, parent.onStart, self.btnStart)
        self.btnStop = wx.Button(self, -1, "Stop MIDI input")
        self.Bind(wx.EVT_BUTTON, parent.onStop, self.btnStop)
        self.btnStop.Enable(False)
        self.btnRandom = wx.Button(self, -1, "Generate random")
        self.btnRandom.Enable(False)
        self.Bind(wx.EVT_BUTTON, parent.onGenerateRandomRythm, self.btnRandom)
        
        self.btnPlay = wx.Button(self, -1, "Play sequence")
        self.Bind(wx.EVT_BUTTON, parent.onPlay, self.btnPlay)
        self.btnExport = wx.Button(self, -1, "export sequence")
        self.Bind(wx.EVT_BUTTON, parent.onExport, self.btnExport)
        
        self.btnConfigMidi = wx.Button(self, -1, "Configure MIDI input")
        self.Bind(wx.EVT_BUTTON, parent.OnSelectMidiPort, self.btnConfigMidi)
        
        sizer=wx.GridSizer(2,3)
        sizer.Add(self.btnStart)
        sizer.Add(self.btnStop)
        sizer.Add(self.btnRandom)
        sizer.Add(self.btnPlay)
        sizer.Add(self.btnExport)
        sizer.Add(self.btnConfigMidi)
        self.SetSizerAndFit(sizer)

class ListCtrlSamples(wx.ListCtrl,
                   listmix.ListCtrlAutoWidthMixin,
                   listmix.TextEditMixin):
    """ An editable list control that handles the samples """

    def __init__(self, parent, ID, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0):
        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)

        listmix.ListCtrlAutoWidthMixin.__init__(self)
        self.Populate()
        listmix.TextEditMixin.__init__(self)
        
        self.samples = []

        self.Bind(wx.EVT_TEXT_ENTER, self.onEnterKeyPressed)


    def onEnterKeyPressed(self, evt):
        try:
            value = int(evt.GetString())
            self.samples[self.curRow].vel = value
        except:
            self.SetStringItem(self.curRow, self.curCol, "0")
            self.samples[self.curRow].vel = 0
            wx.MessageBox("0<=Velocity<=127\n\
                          0 has been assigned to the variable for now",
                          "Error", wx.ICON_ERROR | wx.OK)
        evt.Skip()
        
    
    def Populate(self):
        """ generates the list columns appearance """
        self.InsertColumn(0, "Sample name")
        self.InsertColumn(1, "vel.")
        self.InsertColumn(2, "length")
        self.SetColumnWidth(0, 400)
        self.SetColumnWidth(1, 50)
        self.SetColumnWidth(2, 50)
        self.currentItem = 0
    
    def OpenEditor(self, col, row):
        """ filters the editing only on the vel. column """
        if col==1:
            listmix.TextEditMixin.OpenEditor(self, col, row)
        
    def addSamples(self, paths):
        """ create the Sample instances and populate the list """
        for samplePath in paths:
            sample = Sample(samplePath)
            self.samples.append(sample)
            index = self.InsertStringItem(sys.maxint, sample.path)
            self.SetStringItem(index, 1, str(sample.vel))
            self.SetStringItem(index, 2, str(sample.length))
        
            
    def getSamples(self):
        """ returns the samples"""
        return self.samples

class Sample(object):
    """ A sample audio file container class """
    def __init__(self, path):
        path = str(path)
        self.path = path
        self.vel = 0
        self.length = 0
        try:
            wf = wave.open(path, 'rb')
            self.length = (1.0 * wf.getnframes()) / wf.getframerate()
        except Exception, msg:
            print "Error while analyzing the sample: ",msg
    def __str__(self):
        return "path:%s\nlength:%f\nvelocity:%d"%(self.path, self.length,
                                                  self.vel)


class FreeRythm(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, -1, size=(800,380),
                          style=wx.MINIMIZE_BOX|wx.CLOSE_BOX|wx.CAPTION|wx.SYSTEM_MENU)
        
        self.isAquiring = False
        self.midiEvents = []
        #midi port
        self.port = 0
        
        self.commandPanel = CommandPanel(self)
        self.plot = mYPlotPanel(self)
        self.list = ListCtrlSamples(self, -1, size=(-1, 300),
                                    style=wx.LC_REPORT
                                    | wx.BORDER_NONE
                                    | wx.LC_SORT_ASCENDING)
        dt = MyFilesDropTarget(self)
        self.list.SetDropTarget(dt)
        
        self.mp3Playing = None
        
        sizer = wx.BoxSizer(wx.VERTICAL)
        
        sizer.Add(self.plot)
        sizer.Add(self.list, flag=wx.EXPAND)
        sizer.Add(self.commandPanel, flag=wx.EXPAND)
        
        self.Bind(wx.EVT_CLOSE, self.onClose, self)
        
        self.statusBar = self.CreateStatusBar()
        self.statusBar.SetStatusText("Application succesfully initialized...")
        
        self.SetSizerAndFit(sizer)
        self.Show(True)
        
    def onClose(self, evt):
        """ stops the thread and exits """
        #TODO: ... hem hem
        self.isAquiring = False
        self.Destroy()
    
    
    def onGenerateRandomRythm(self, event):
        #TODO: change algo: big random, and between them smaller ones to give the
        #          "impression" of a "real" rhythm
        del self.midiEvents[:]
        offsetTime = 0
        timeDebut = time()
        for i in xrange(10):
            self.midiEvents.append(MidiEvent(((timeDebut+offsetTime)-timeDebut)/1000.0,
                                             random.randint(1, 127)))
            offsetTime += random.randint(1000, 1500)
        print "randomizing finished"
        self.statusBar.SetStatusText("Randomizing finished")
        self._updateGraph()
        self._generate()

    def _updateGraph(self):
        whens = []
        vels = []
        for midiEvent in self.midiEvents:
            whens.append(midiEvent.when)
            vels.append(midiEvent.vel)
        self.plot.setMidiEvents(whens, vels)
        self.plot.draw()
        self.plot.canvas.draw()

    def onStart(self, evt):
        """ starts the midi input """
        self.statusBar.SetStatusText("Midi input started using port %d..."%self.port)
        del self.midiEvents[:]
        self.commandPanel.btnStart.Enable(False)
        self.commandPanel.btnStop.Enable(True)
        self.isAquiring = True
        thread.start_new_thread(self._aquire, (self.port,))
    
    def onStop(self, evt):
        """stops the midi input, updates the graph and generate the sequence"""
        self.statusBar.SetStatusText("Midi input finished")
        self.isAquiring = False
        self.commandPanel.btnStart.Enable(True)
        self.commandPanel.btnStop.Enable(False)
        if self.midiEvents!= []:
            self._updateGraph()
            self._generate()

    def onPlay(self, evt):
        evt.Skip()
        
    def onExport(self, evt):
        """ export to a mp3 file """
        #TODO:renoise xml version
        print "TODO:EXPORT"
    
    
    def _generate(self):
        """ generate the audio sequence from the samples in the list """
        self.statusBar.SetStatusText("Generation of the sequence...")
        samples = self.list.getSamples()
        for sample in samples:
            print sample
        
        #for testing purpose only, real algo to come
        
        #start time of the last sample, to know how much blank time we must add
        lastSampleEnded = 0.0
        for midiEvent in self.midiEvents:
            print "------------------------------------------"
            print "appending midi event ",midiEvent
            #TODO algorithm to select the sample
            selectedSample = 1
            
            path = samples[selectedSample].path
            length = samples[selectedSample].length/1000.0 # ms->s
            
            when = midiEvent.when
            
            
            if lastSampleEnded!= 0.0:
                #we add a blank from lastSampleEnded to when
                pass
            
            #and then the sample from when to when+length
            
            #and we update the last played offset
            lastSampleEnded = when+length
        
        self.statusBar.SetStatusText("Generation of the sequence terminated")
    
    def _aquire(self, args):
        """ thread aquiring midi data """
        print MidiDeviceList()  # List devices (only on WIN)

        # midi stuff: note (midi note)
        midi = SndMidiIn(self.port, 10)#buffer 10: default 64... ok?
        note = MidiIn(midi)
        timeDebut = time()
        while self.isAquiring:
            midi.Read() 
            note.DoProcess()
             
            if midi.NoteOn() != -1:             # if a new note is detected
                cur_note = midi.LastNote()      # set the cur_note to its value
                self.midiEvents.append((MidiEvent(time()-timeDebut)/1000.0,
                                                 ord(midi.Velocity(cur_note))))
        print "aquiring over"
        
    def OnSelectMidiPort(self, evt):
        #TODO show the available ports
        dlg = wx.TextEntryDialog(
                self, "Enter the port number",
                'Midi port configuration', '')

        dlg.SetValue("1")

        if dlg.ShowModal() == wx.ID_OK:
            try:
                self.port = int(dlg.GetValue())
                dlg.Destroy()
            except:
                wx.MessageBox("Enter a valid number please",
                          "input error", wx.ICON_ERROR | wx.OK)


    def OnDropFiles(self, filenames):
        #onlyFileNames = [f[f.rfind("\\")+1:] for f in filenames]
        self.list.addSamples(filenames)
        self.commandPanel.btnRandom.Enable(True)
        self.statusBar.SetStatusText("Don't forget to tune the velocities of the dropped samples...")
    
class MyFilesDropTarget(wx.FileDropTarget):
    """ Used to drop multiples samples """
    def __init__(self, obj):
        wx.FileDropTarget.__init__(self)
        self.obj = obj

    def OnDropFiles(self, x, y, filenames):
        self.obj.OnDropFiles(filenames)

if __name__=="__main__":
    app = wx.App()
    app.RestoreStdio()
    FreeRythm(None)
    app.MainLoop()